package com.chipcoo.utils;

import com.chipcoo.utils.hash.MurmurHash3;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class CryptoUtils {
    public static String byte2Hex(byte[] paramArrayOfByte){
        int iLen = paramArrayOfByte.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < iLen; i++) {
            sb.append( String.format("%02x",paramArrayOfByte[i]&0xFF ) );
        }
        return sb.toString();
    }
    private static byte[] encrypt(byte[] paramArrayOfByte,  String hash_algorithm) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(hash_algorithm);
        md.update(paramArrayOfByte);
        return md.digest();
    }

    public static  byte[] md5(byte[] paramArrayOfByte) throws NoSuchAlgorithmException {
        return encrypt(paramArrayOfByte, "MD5");
    }

    public static String md5( String text){
        return md5(text, null);
    }
    public static String md5( String text,String textEncoding) {
        if(StringUtils.isEmpty(text)) return null;
        try {
            return byte2Hex(md5(text.getBytes(null == textEncoding?"UTF-8":textEncoding)));
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    public static String murmurhash3_x64_128( String text){
        return murmurhash3_x64_128(text, null);
    }
    public static String murmurhash3_x64_128( String text,String textEncoding) {
        if(StringUtils.isEmpty(text)) return null;
        try {
            return  murmurhash3_x64_128(text.getBytes(null == textEncoding?"UTF-8":textEncoding));
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    private static String murmurhash3_x64_128(byte[] paramArrayOfByte){
        MurmurHash3.LongPair longPair = new MurmurHash3.LongPair();
        MurmurHash3.murmurhash3_x64_128(paramArrayOfByte,0,paramArrayOfByte.length,31,longPair);
        //return ("00000000" + (h1[0] >>> 0).toString(16)).slice(-8)
        //+ ("00000000" + (h1[1] >>> 0).toString(16)).slice(-8)
        //+ ("00000000" + (h2[0] >>> 0).toString(16)).slice(-8)
        //+ ("00000000" + (h2[1] >>> 0).toString(16)).slice(-8);
        return String.format("%s%s",
                Long.toHexString(longPair.val1),
                Long.toHexString(longPair.val2)
        );
    }
}